package com.frank.code_notes.C02_LinkedList;


import cn.hutool.core.lang.Console;
import com.frank.utils.ListNode;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @Description 206.反转链表
 * @Author zhoujr
 * @Data 2024/12/3 21:04
 */
public class L206InvertLinkedList {

    /**
     * @Description 双指针法
     */
    public static ListNode reverseList(ListNode head) {
        ListNode left = null;
        ListNode right = head, temp;
        while (right != null) {
            temp = right.next;
            right.next = left;
            left = right;
            right = temp;
        }
        return left;
    }

    /**
     * @Description 递归调用
     */
    public static ListNode reverse(ListNode prev, ListNode cur) {
        if (cur == null) {
            return prev;
        }
        ListNode temp = cur.next;
        cur.next = prev;
        return reverse(cur, temp);
    }

    public static void linkedPrint(ListNode cur) {
        Console.log("入栈");
        if (cur != null) {
            Console.log(cur.val);
            linkedPrint(cur.next);
        }
        Console.log("出栈");

        Console.log(cur != null ? cur.val : "null");
    }

    public static void main(String[] args) {
        linkedPrint(reverseList(ListNode.toListNode(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)))));

        ListNode reverse = reverse(null, ListNode.toListNode(new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5))));
        linkedPrint(reverse);
    }

}
